<template>
  <div class="title">上架商品</div>
  <c-main-template
    class="mr-24 ml-24 mb-24"
    minHeight="auto"
    :isBreadcrumb="false"
    v-loading="loading"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="auto"
      size="large"
      status-icon
    >
      <el-row :gutter="24" class="pr-lg pl-lg pb-lg pt-30">
        <!-- 待审核 -->
        <el-alert
          v-if="ruleForm.status === 0"
          class="mb-30"
          title="平台审核中，请耐心等待。"
          type="warning"
          show-icon
        />
        <!-- 已驳回 -->
        <el-alert
          v-if="ruleForm.status === 1"
          class="mb-30"
          :title="`审核未通过，驳回原因：${ruleForm.remarks}`"
          type="error"
          show-icon
        />
        <el-col :span="24" class="subtitle"> 基本信息 </el-col>
        <el-col :span="8">
          <el-form-item label="商品标题" prop="productTitle">
            <el-input
              :disabled="isDisabled"
              v-model="ruleForm.productTitle"
              placeholder="请输入商品标题"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车辆信息" prop="carInfoId">
            <c-vehicle-select
              :disabled="isDisabled"
              v-model="ruleForm.carInfoId"
              placeholder="请选择车辆信息"
              size="large"
              class="wh"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库存数量" prop="stockAmount">
            <c-number-input
              :disabled="isDisabled"
              v-model="ruleForm.stockAmount"
              placeholder="请输入库存数量"
            >
              <template #append>台</template>
            </c-number-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="可接受付汇方式" prop="payModeList">
            <el-select
              v-model="ruleForm.payModeList"
              placeholder="请选择可接受成交方式"
              size="large"
              class="wh"
              :disabled="isDisabled"
              multiple
            >
              <el-option
                v-for="(item, index) in paymentMethod"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="启运港" prop="startHarborId">
            <c-port-select
              v-model="ruleForm.startHarborId"
              placeholder="请选择启运港"
              size="large"
              class="wh"
              :disabled="isDisabled"
            />
          </el-form-item>
        </el-col>
        <el-divider />
        <el-col :span="24" class="subtitle"> 商品价格 </el-col>
        <el-col :span="24" class="pd-0">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="车辆价格" prop="productPrice" class="is-required" >
                <c-money-input
                  v-model="ruleForm.productPrice"
                  placeholder="请输入车辆价格"
                  :disabled="isDisabled"
                >
                  <template #prepend>
                    <el-select
                      v-model="ruleForm.productCurrency"
                      placeholder="请选择币种"
                      :disabled="isDisabled"
                      size="large"
                    >
                      <el-option
                        v-for="(item, index) in currencyType"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                  <template #append>台</template>
                </c-money-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="可接受成交方式" prop="tradeModeList">
                <el-select
                  v-model="ruleForm.tradeModeList"
                  @change="onPayModeChange"
                  placeholder="请选择可接受成交方式"
                  size="large"
                  :disabled="isDisabled"
                  class="wh"
                  value-key="code"
                  multiple
                >
                  <el-option
                    v-for="(item, index) in termsDeliveryList"
                    :key="index"
                    :label="item.code"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <!-- 循环处理 -->
        <el-col
          :span="24"
          class="pd-0"
          v-for="(t, j) in ruleForm.tradeModeList"
          :key="j"
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item
                :label="t.code"
                :prop="`tradeModeList.${j}.price`"
                :rules="getTradeModeListRules(t)"
                class="is-required"
              >
                <c-money-input
                  :disabled="isDisabled"
                  v-model="t.price"
                  placeholder="请输入价格"
                >
                  <template #prepend>
                    <el-select
                      v-model="t.currency"
                      placeholder="请选择币种"
                      size="large"
                      :disabled="isDisabled"
                    >
                      <el-option
                        v-for="(item, index) in currencyType"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </template>
                  <template #append>台</template>
                </c-money-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="约定付款时间"
                :prop="`tradeModeList.${j}.payTimeNode`"
                :rules="rules.payTimeNode"
              >
                <el-select
                  v-model="t.payTimeNodeList"
                  multiple
                  placeholder="请选择约定付款时间"
                  :disabled="isDisabled"
                  size="large"
                  class="wh"
                >
                  <el-option
                    v-for="(item, index) in timePayments(t)"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-divider />
        <el-col :span="24" class="subtitle"> 商品展示 </el-col>
        <el-col :span="24">
          <el-form-item prop="prodcutPicList.thumbnailUrl">
            <template #label>
              <span>缩略图</span>
              <span class="ml-lg el-form-item__describe"
                >支持.png、.jpg，且大小不超过2M</span
              >
            </template>
            <c-image-upload
              type="String"
              limit="1"
              :disabled="isDisabled"
              :accept="['.png', '.jpg']"
              v-model="ruleForm.prodcutPicList.thumbnailUrl"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="prodcutPicList.slideshowUrls">
            <template #label>
              <span>轮播图</span>
              <span class="ml-lg el-form-item__describe"
                >支持.png、.jpg，且大小不超过2M，最多不超过4张</span
              >
            </template>
            <c-image-upload
              limit="4"
              :disabled="isDisabled"
              :accept="['.png', '.jpg']"
              v-model="ruleForm.prodcutPicList.slideshowUrls"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="video">
            <template #label>
              <span>视频</span>
              <span class="ml-lg el-form-item__describe"
                >支持.mp4格式，大小不超过500M,仅支持 上传一个视频</span
              >
            </template>
            <c-video-upload
              :disabled="isDisabled"
              type="String"
              size="500"
              v-model="ruleForm.video"
              :accept="['.mp4']"
              :limit="1"
            />
          </el-form-item>
        </el-col>
        <el-divider />
        <el-col :span="24" class="subtitle"> 商品详情 </el-col>
        <el-col :span="24">
          <el-form-item prop="productDetails">
            <c-tinymce
              :disabled="isDisabled"
              class="wh"
              placeholder="请输入商品详情"
              v-model="ruleForm.introduce"
            />
          </el-form-item>
        </el-col>

        <!-- 操作 -->
        <el-col :span="24">
          <!-- 不等于待审核的时候 -->
          <el-button
          v-if="![0,2].includes(ruleForm.status)"
            type="primary"
            @click="handleSubmit"
            :loading="buttonLoading"
          >
            <span v-if="route.query.copy"> 发布商品 </span>
            <!-- 什么都没有的情况 草稿或者新增的情况-->
            <span v-else-if="ruleForm.status === null">发布商品</span>
            <!-- 已驳回的时候 -->
            <span v-else-if="ruleForm.status === 1">再次申请</span>
            <!-- 下架的时候 -->
            <span v-else-if="ruleForm.status === 3">重新上架</span>
          </el-button>
          <el-button
            :loading="buttonLoading"
            @click="handleDraft"
            v-if="ruleForm.status === null"
          >
            <span>保存草稿</span>
          </el-button>
          <!-- 上架的情况 -->
          <el-button
            :loading="buttonLoading"
            @click="handleSoldOut"
            v-if="ruleForm.status === 2"
          >
            <span>下架商品</span>
          </el-button>
        </el-col>
      </el-row>
    </el-form>
  </c-main-template>
</template>
<script setup>
import { ref, onMounted, computed, getCurrentInstance } from "vue";
import cImageUpload from "@/components/Upload/ImageUpload.vue";
import cVideoUpload from "@/components/Upload/VideoUpload.vue";
import cTinymce from "@/components/Tinymce/index.vue";
import { usePublishGoodsForm } from "./components/index.js";
import { deepClone } from "@/utils/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  currencyType,
  termsDeliveryType,
  paymentMethod,
} from "@/utils/status.js";
import { useRoute, useRouter } from "vue-router";
const termsDeliveryList = ref(deepClone(termsDeliveryType));
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const ruleFormRef = ref();
const ruleForm = ref({
  status: null,
  payModeList: [],
  tradeModeList: [],
  // 车辆图片
  prodcutPicList: {},
});
const draftsInfo = ref(null);
const loading = ref(false);
const buttonLoading = ref(false);
onMounted(() => {
  getById()
});
const isDisabled = computed(() => {
  const status = ruleForm.value.status;
  if ([0, 2].includes(status)) {
    return true;
  }
  return false;
});
const timePayments = computed(() => {
  return (t) => {
    const d = termsDeliveryType.find((x) => {
      return x.code === t.code;
    });
    return d.list || [];
  };
});
const onPayModeChange = (item) => {
  const form = deepClone(ruleForm.value);
  const data = item.map((x) => {
    if (!x.currency && form.productCurrency) {
      x.currency = form.productCurrency;
    }
    if (!x.price && form.productPrice) {
      x.price = form.productPrice;
    }
    if(!x.payTimeNodeList && x.code) {
      x.payTimeNodeList = [timePayments.value(x)[0].value]
    }
    return x;
  });
  console.log(data);
  ruleForm.value.tradeModeList = data
};
const getById = async () => {
  // index === 0 草稿
  // copy  复制
  // id 详情
  try {
    const querys = route.query || null;
    let url;
    if (querys.index) {
      loading.value = true;
      url = "/draft/get";
      const data = {
        business: 2,
        index: querys.index,
      };
      const res = await proxy.$post({ url, data });
      const d = JSON.parse(JSON.parse(res).data);
      d.status = null;
      ruleForm.value = d;
      draftsInfo.value = res;
    } else if (querys.id) {
      loading.value = true;
      url = "/product/listing/getById";
      const res = await proxy.$get({ url, params: querys });
      const data = Object.assign(res.product, res.productDetail);
      if (querys.copy) {
        data.id = null;
        data.status = null;
      }
      ruleForm.value = data;
    }
    loading.value = false;
    if (ruleFormRef.value) {
      ruleFormRef.value.resetFields();
    }
  } catch (error) {
    loading.value = false;
  }
};
const handleSoldOut = () => {
  ElMessageBox.confirm("是否确认此操作?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const url = "/product/listing/off?id=" + ruleForm.value.id;
    // 后端只要id
    await proxy.$post({ url});
    ElMessage.success("操作成功");
    router.go(-1);
  });
};
const handleSubmit = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let url;
      const data = deepClone(ruleForm.value);
      if (data.id) {
        url = "/product/listing/reapply";
      } else {
        url = "/product/listing/apply";
      }
      buttonLoading.value = true;
      try {
        await proxy.$post({ url, data });
        deleteDraft();
      } catch (error) {
        buttonLoading.value = false;
      }
    }
  });
};
const handleDraft = async () => {
  const url = "/draft/save";
  const data = {
    business: 2,
    data: JSON.stringify(ruleForm.value),
  };
  try {
    buttonLoading.value = true;
    await proxy.$post({ url, data });
    deleteDraft();
  } catch (error) {
    buttonLoading.value = false;
  }
};
const deleteDraft = async () => {
  if (draftsInfo.value) {
    const url = "/draft/delete";
    const data = {
      business: 2,
      data: draftsInfo.value,
    };
    await proxy.$post({ url, data });
    ElMessage.success("操作成功");
    router.go(-1);
  } else {
    buttonLoading.value = false;
    ElMessage.success("操作成功");
    router.go(-1);
  }
};
const { rules, getTradeModeListRules } = usePublishGoodsForm(ruleForm);
</script>
<style lang="less" scoped>
:deep(.el-input-group__prepend) {
  width: 90px;
}
.title {
  font-size: 16px;
  font-weight: 500;
  color: #26282a;
  margin-top: 24px;
  margin-bottom: 16px;
  margin-left: 24px;
}
.subtitle {
  font-size: 16px;
  font-weight: 500;
  color: #202020;
  margin-bottom: 20px;
}
.el-form-item__describe {
  font-size: 12px;
  color: #8d9297;
}
</style>